<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\RoleRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    public function index()
    {
        $roles = Role::all();
        return $roles;
    }


    public function store(RoleRequest $request)
    {
        Role::create(['name' => $request->name, 'title' => $request->title]);
        return $this->message('创建成功');
    }

    /**
     * 为管理员设置角色
     * @param Request $request
     * @param user $user
     * @return array
     */
    public function syncRoles(Request $request, user $user)
    {

        $user->syncRoles($request->currentRoles);
        return $this->message('角色设置成功');
    }

    public function show(Role $role)
    {
        return $role;
    }

    public function edit(Role $role)
    {
        return $role;
    }

    public function update(Request $request, Role $role)
    {
        $role->fill($request->input());
        $role->save();
        return $this->message('角色编辑成功');
    }

    public function destroy(Role $role)
    {
        $role->delete();

        return $this->message('角色删除成功');
    }

    /**
     * 获取角色的权限
     * @param Role $role
     * @return \Illuminate\Support\Collection
     *
     */
    public function permissions(Role $role)
    {
        return $role->permissions()->pluck('name');
    }

    /**
     * 获取当前管理员的角色
     */

    public function hasRoles(User $user)
    {
        return $user->getRoleNames();
    }
}
